<template>
  <div class="tool-left">
    <a-form layout="inline">
      <a-form-item
        :label="windowWidth >= 1000 ? '视图名称' : ''"
        :validate-status="validate"
        :help="help"
      >
        <a-input
          v-model="name"
          @change="handleViewName"
          placeholder="请输入视图名称"
        ></a-input>
      </a-form-item>
      <template v-if="windowWidth >= 1000">
        <a-form-item>
          <a-button @click="handleSave" type="primary">
            <svg-icon :type="tooler.save.icon" />
            {{ tooler.save.label }}
          </a-button>
        </a-form-item>
        <a-form-item>
          <a-button v-btn="['preview', '', $route.params.id]"></a-button>
        </a-form-item>
      </template>
    </a-form>
  </div>
</template>

<script>
import window from '@/mixins/window'
import tool from '@/mixins/tooler'

import { createNamespacedHelpers } from 'vuex'

const { mapState, mapMutations } = createNamespacedHelpers('editor')

import {
  APIUploadViewCover,
  APIEditConfigureViews,
  APIDeleteViewCover,
} from '@/api/editor'

import { dataURLtoBlob, uniqueId } from '@/utils'

import * as setter from '@/setter'

export default {
  name: 'ToolLeft',
  mixins: [window, tool],
  data() {
    return {
      name: '',
      _name: '',
      validate: '',
      help: '',
    }
  },
  computed: {
    ...mapState(['schema']),
  },
  watch: {
    'schema.name': {
      immediate: true,
      handler(val, oldVal) {
        // console.log('schema.name', val)
        this.name = val
      },
    },
  },
  methods: {
    ...mapMutations(['handleName']),
    handleViewName() {
      if (this.name.length > 6) {
        this.validate = 'error'
        this.help = '视图名称最多输入6个汉字！'
      } else if (this.name.length < 1) {
        this.validate = 'error'
        this.help = '视图名称不能为空！'
      } else {
        this.validate = ''
        this.help = ''
        this.handleName(this.name)
      }
    },
    handleValidator() {//NOSONAR
      console.log('this.getComponentList.length', this.getComponentList.length)
      // 对meta进行校验
      if (this.getComponentList.length > 0) {
        const temp = {};
        for (let i = 0; i < this.getComponentList.length; i++) {
          let meta = this.getComponentList[i]
          console.log('meta', meta)
          if (setter[meta.key]?.validator) {
            const props = Object.keys(meta.prop)
            for (let j = 0; j < props.length; j++) {
              let p = props[j]
              const r = setter[meta.key].validator[p](meta.prop[p])
              if (!r) {
                return
              }
            }
          }
          temp[meta.id] = {
            prop: meta.prop,
            global: meta.global,
            attr: meta.attr,
            key: meta.key,
            zIndex: meta.zIndex,
            DELETE: meta.DELETE,
            RESIZE: meta.RESIZE,
            UPDATE: meta.UPDATE,
          }
        }
        this.handleMeta(temp)
      } else {
        this.handleMeta({})
      }
    },
    handleViewValue() {//NOSONAR
      console.log('this.schema', this.schema)

      if (this.canvasImg) {
        // 保存
        const save = (viewCoverAddress, isIncrease) => {
          const [, fileName] = viewCoverAddress.split('/')
          APIEditConfigureViews({
            viewId: this.schema.viewId,
            viewName: this.schema.name,
            viewValue: JSON.stringify(this.schema),
            viewCoverAddress,
          })
            .then((result) => {
              if (result.code == 0) {
                this.$message.success('保存成功')
                return true;
              } else {
                throw new Error(result.msg)
              }
            })
            .then(flag => {
              if(flag) {
                this.$router.go(0)
              }
            }) 
            .catch(async (err) => {
              if (isIncrease) {
                // 删除已上传封面
                const formData = new FormData()
                formData.append('fileName', fileName)
                formData.append('prefixUrl', '')
                APIDeleteViewCover(formData)
              }
              this.$message.error(`保存失败，${err}`)
            })
        }

        if (this.canvasImg != this.schema.thumbnail) {
          // 如果封面变化了
          this.handleThumbnail(this.canvasImg)
          const blob = dataURLtoBlob(this.canvasImg)
          // console.log('blob', blob)
          const data = new FormData()
          data.append(
            'file',
            blob,
            `lcd_${uniqueId(this.$route.params.id)}.png`,
          )
          // 上传封面
          APIUploadViewCover(data)
            .then((res) => {
              // console.log('res', res)
              if (res.code == 0) {
                this.$message.success(`封面上传成功`)
                return res.data.fileName
              } else {
                throw new Error(res.msg)
              }
            })
            .then((fileName) => {
              // 删除schema中的cover封面
              if(this.schema.cover) {
                const formData = new FormData()
                formData.append('fileName', this.schema.cover)
                formData.append('prefixUrl', '')
                APIDeleteViewCover(formData)
                this.handleCover('')
              }
              return fileName
            })
            .then((fileName) => {
              this.handleCover(`gesp/${fileName}`)
              save(`gesp/${fileName}`, true)
            })
            .catch((e) => {
              this.$message.error(e)
            })
        } else {
          save(this.schema.cover, false)
        }
      } else {
        this.$message.info('暂无封面')
      }
    },
    // @override 重写save操作
    async handleSave() {//NOSONAR
      this.handleViewId(this.$route.params.id)
      this.handleValidator();
      this.handleViewValue();
    },
  },
}
</script>

<style lang="less" scoped>
@import '~@/styles/cover.less';
/deep/ .ant-form-explain {
  margin-top: -0.375rem;
}
.tool-left {
  display: flex;
  align-items: center;
  position: absolute;
  top: 6px;
  .ant_btn_reset();
  .ant_input_reset();
}
</style>
